package cn.happy.favdish.view.fragments

import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import cn.happy.favdish.R
import cn.happy.favdish.application.FavDishApplication
import cn.happy.favdish.databinding.DialogCustomListBinding
import cn.happy.favdish.databinding.FragmentHomeBinding
import cn.happy.favdish.model.entities.FavDish
import cn.happy.favdish.utils.Constants
import cn.happy.favdish.view.activities.AddUpdateDishActivity
import cn.happy.favdish.view.activities.MainActivity
import cn.happy.favdish.view.adapter.CustomListItemAdapter
import cn.happy.favdish.view.adapter.FavDishAdapter
import cn.happy.favdish.view.viewmodel.FavDishViewModel
import cn.happy.favdish.view.viewmodel.FavDishViewModelFactory
import cn.happy.favdish.view.viewmodel.HomeViewModel

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val mFavDishViewModel: FavDishViewModel by viewModels {
        FavDishViewModelFactory((requireActivity().application as FavDishApplication).repository)
    }

    private lateinit var mFavDishAdapter: FavDishAdapter
    private lateinit var mCustomListItemAdapter: CustomListItemAdapter

    private lateinit var mCustomListDialog: Dialog

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val homeViewModel =
            ViewModelProvider(this)[HomeViewModel::class.java]

        _binding = FragmentHomeBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val menuHost: MenuHost = requireActivity()

        menuHost.addMenuProvider(object  : MenuProvider{
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menuInflater.inflate(R.menu.menu_home,menu)
            }

            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                when(menuItem.itemId){
                    R.id.action_add_dish -> {
                        startActivity(Intent(requireActivity(),AddUpdateDishActivity::class.java))
                    }
                    R.id.action_filter_dishes -> {
                        filterDishesListDialog()
                    }
                }
                return true
            }
        },viewLifecycleOwner,Lifecycle.State.RESUMED)

        binding.rvDishesList.layoutManager = GridLayoutManager(requireActivity(),2)
        mFavDishAdapter = FavDishAdapter(this)
        binding.rvDishesList.adapter = mFavDishAdapter

        mFavDishViewModel.allDishesList.observe(viewLifecycleOwner){
            dishes ->
            dishes.let{
                if(it.isNotEmpty()){
                    binding.rvDishesList.visibility = View.VISIBLE
                    binding.tvNoDishesAddedYet.visibility = View.GONE
                    mFavDishAdapter.dishesList(it)
                }else{
                    binding.rvDishesList.visibility = View.GONE
                    binding.tvNoDishesAddedYet.visibility = View.VISIBLE
                }

            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(requireActivity() is MainActivity){
            (activity as MainActivity?)?.showBottomNavigationView()
        }
    }

    // 列表点击 进入详情页面
    fun dishDetails(favDish:FavDish){
        val bundle = Bundle()
        bundle.putParcelable("fav_dish",favDish)
        findNavController().navigate(R.id.action_navigation_home_to_dishDetailsFragment,bundle)
        if(requireActivity() is MainActivity){
            (activity as MainActivity?)?.hideBottomNavigationView()
        }
    }

    // 删除列表条目
    fun deleteDish(favDish: FavDish){
        val builder= AlertDialog.Builder(requireActivity())
        builder.setTitle(getString(R.string.title_delete_dish))
        builder.setMessage(getString(R.string.msg_delete_dish,favDish.title))
        builder.setIcon(android.R.drawable.ic_delete)
        builder.setPositiveButton(resources.getString(R.string.delete)) { dialogInterface,_ ->
            mFavDishViewModel.delete(favDish)
            dialogInterface.dismiss()
        }
        builder.setNegativeButton(resources.getString(R.string.cancel)){dialogInterface,_ ->
            dialogInterface.dismiss()
        }
        val alertDialog = builder.create()
        alertDialog.setCancelable(false)
        alertDialog.show()
    }

    // 筛选菜单
    fun filterDishesListDialog(){
        mCustomListDialog = Dialog(requireActivity())
        val binding: DialogCustomListBinding = DialogCustomListBinding.inflate(layoutInflater)

        mCustomListDialog.setContentView(binding.root)
        binding.dialogListTvTitle.text = resources.getString(R.string.title_select_item_to_filter)

        val dishTypes = Constants.dishTypes()
        dishTypes.add(0,Constants.ALL_TYPES)
        binding.dialogRvList.layoutManager = LinearLayoutManager(requireActivity())

        mCustomListItemAdapter = CustomListItemAdapter(requireActivity(),this,dishTypes,Constants.ALL_TYPES)
        binding.dialogRvList.adapter = mCustomListItemAdapter

        mCustomListDialog.show()
    }

    fun filterSelection(filterItemSelection: String){
        mCustomListDialog.dismiss()

        if(filterItemSelection == Constants.ALL_TYPES){
            mFavDishViewModel.allDishesList.observe(viewLifecycleOwner){
                    dishes ->
                dishes.let{
                    if(it.isNotEmpty()){
                        binding.rvDishesList.visibility = View.VISIBLE
                        binding.tvNoDishesAddedYet.visibility = View.GONE
                        mFavDishAdapter.dishesList(it)
                    }else{
                        binding.rvDishesList.visibility = View.GONE
                        binding.tvNoDishesAddedYet.visibility = View.VISIBLE
                    }

                }
            }
        }else{
            // 根据条件筛选列表
            mFavDishViewModel.filterDishList(filterItemSelection).observe(viewLifecycleOwner){
                    dishes ->
                dishes.let{
                    if(it.isNotEmpty()){
                        binding.rvDishesList.visibility = View.VISIBLE
                        binding.tvNoDishesAddedYet.visibility = View.GONE
                        mFavDishAdapter.dishesList(it)
                    }else{
                        binding.rvDishesList.visibility = View.GONE
                        binding.tvNoDishesAddedYet.visibility = View.VISIBLE
                    }

                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }


}